package com.iworkh.spring.data.jdbc.tx.dao;

import com.iworkh.spring.data.jdbc.tx.domain.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

/**
 * BookDao
 *
 * @author: iworkh-沐雨云楼
 * @date: 2019-12-20
 */
@Repository
public class BookDao {

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public void save(Book book) {
        System.out.println(namedParameterJdbcTemplate);
    }

    public int getCount(String id){
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("id", id);

        String sqlCount = "select count from book where id=:id";

        return namedParameterJdbcTemplate.queryForObject(sqlCount, paraMap, Integer.class);

    }

    public void sellOne(String id) throws RuntimeException {

        if (this.getCount(id) < 1) {
            throw new RuntimeException("库存不足");
        }

        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("id", id);

        String sql = "update book set count=count-1 where id=:id";

        namedParameterJdbcTemplate.update(sql, paraMap);
    }
}
